package com.example.redisdemo.Controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 使用lua脚本实现分布式锁
 */
@RestController
@RequestMapping("/redis")
public class TestLockPlus {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @GetMapping("/test2")
    public void testLockLua() {
        String uuid = UUID.randomUUID().toString();
        String skuId = "25"; // 访问skuId 为25号的商品 100008348542
        String locKey = "lock:" + skuId; // 锁住的是每个商品的数据
        Boolean aBoolean = RedisUtils.setLock(redisTemplate,locKey, uuid);

        try {
            if (Boolean.TRUE.equals(aBoolean)) {
                Object value = redisTemplate.opsForValue().get("num");
                if (Objects.isNull(value)) {
                    redisTemplate.opsForValue().set("num","1",20,TimeUnit.SECONDS);
                }
                value = redisTemplate.opsForValue().get("num");
                System.out.println("value：" + value);
                int num = Integer.parseInt(value + "");
                redisTemplate.opsForValue().set("num", String.valueOf(++num),20,TimeUnit.SECONDS);
            } else {
                try {
                    Thread.sleep(1000);
                    // 睡醒了之后，调用方法。
                    testLockLua();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            RedisUtils.delLock(redisTemplate,locKey,uuid);
        }
    }
}
